package com.dgut.courses_selecting_sys.shiro.filter;

import com.dgut.courses_selecting_sys.constants.ShiroConstants;
import com.dgut.courses_selecting_sys.entity.AjaxResult;
import com.dgut.courses_selecting_sys.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 登录帐号控制过滤器
 *
 * @author ruoyi
 */
public class KickoutSessionFilter extends AccessControlFilter {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 同一个用户最大会话数
     **/
    private int maxSession =1;

    /**
     * 踢出之前登录的/之后登录的用户 默认false踢出之前登录的用户
     **/
    private Boolean kickoutAfter = false;
    private static String KICKOUT="kickout";

    /**
     * 踢出后到的地址
     **/
    private String kickoutUrl;

    private SessionManager sessionManager;
    private Cache<String, Deque<Serializable>> cache;

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o)
            throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest req, ServletResponse resp) throws Exception {
        Subject subject = getSubject(req, resp);
        if (!subject.isAuthenticated() && !subject.isRemembered() || maxSession == -1) {
            return true;
        }
        try {
            Session session = subject.getSession();
            User user = (User) SecurityUtils.getSubject().getPrincipal();
            String loginName = user.getLoginName();
            Serializable sessionId = session.getId();
            Deque<Serializable> deque = cache.get(loginName);
            if (deque == null) {
                deque = new ArrayDeque<>();
            }
            if (!deque.contains(sessionId) && session.getAttribute(KICKOUT) == null) {
                deque.push(sessionId);
                cache.put(loginName, deque);
            }
            while (deque.size() > maxSession) {
                Serializable kickoutSesId ;
                if (kickoutAfter) {
                    kickoutSesId = deque.removeFirst();
                } else {
                    kickoutSesId = deque.removeLast();
                }
                cache.put(loginName, deque);
                try {
                    Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSesId));
                    if (null != kickoutSession) {
                        kickoutSession.setAttribute(KICKOUT, true);
                    }
                } catch (Exception e) {
                }
            }
            if (session.getAttribute(KICKOUT) != null && (Boolean) session.getAttribute(KICKOUT) == true) {
                subject.logout();
                saveRequest(req);
                return isAjaxResponse(req, resp);
            }
            return true;
        } catch (Exception e) {
            return isAjaxResponse(req, resp);
        }
    }

    private boolean isAjaxResponse(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String accept = req.getHeader("accept");
        if (accept != null && accept.indexOf("application/json") != -1) {
            AjaxResult ajaxResult = AjaxResult.error("您已在别处登录，请您修改密码或重新登录");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(ajaxResult);
            return true;
        } else {
            WebUtils.issueRedirect(req, response, kickoutUrl);
        }
        return false;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    // 设置Cache的key的前缀
    public void setCacheManager(CacheManager cacheManager)
    {
        // 必须和ehcache缓存配置中的缓存name一致
        this.cache = cacheManager.getCache(ShiroConstants.SYS_USERCACHE);
    }

}
